import {createCmsEditorOptionUser} from "../../../packages";
import {nextCmsId} from "../../../packages/common/core/cms.utils";
import {env} from "../../env";
import {deepcopy} from "@peryl/utils/deepcopy";
import {http} from "../plain-design/http";
import {$notice} from "plain-design";

export const useCmsEditorOption = createCmsEditorOptionUser({
  assetsPrefix: env.assetsPrefix,
  defaultData: [
    {
      id: nextCmsId(),
      code: 'row',
      label: 'PAGE',
      isRoot: true,
      design: {
        designWidth: 375
      },
      version: 1,
      data: {}
    }
  ],
  queryBindingVariableData: async (queryEntity) => {
    const respQueryEntity = deepcopy(queryEntity);

    const query = (!queryEntity.query ? undefined : (typeof queryEntity.query === "string" ? JSON.parse(queryEntity.query) : queryEntity.query)) || {};
    const body = (!queryEntity.body ? undefined : (typeof queryEntity.body === "string" ? JSON.parse(queryEntity.body) : queryEntity.body)) || {};
    const headers = (!queryEntity.headers ? undefined : (typeof queryEntity.headers === "string" ? JSON.parse(queryEntity.headers) : queryEntity.headers)) || {};

    Object.assign(
      queryEntity.method.toLowerCase() === 'get' ? query : body,
      queryEntity.disablePaginationParameter ? {} : {
        page: queryEntity.page,
        size: queryEntity.pageSize,
        all: queryEntity.queryAllData
      }
    );

    const resp = await http.request<
      { code: number, fail: boolean, message?: string } &
      ({ list: any[], hasNext: boolean } | { result: any })
    >({
      url: queryEntity.url,
      method: queryEntity.method,
      params: query,
      data: body,
      headers: headers,
    });
    if (!!resp.message) {
      respQueryEntity.errorMessage = resp.message;
      respQueryEntity.errorCode = resp.code;
      respQueryEntity.errorData = (resp as any).result;
    } else {
      if ('list' in resp) {
        respQueryEntity.data = resp.list;
        respQueryEntity.loaded = !resp.hasNext;
      } else {
        respQueryEntity.data = resp.result;
      }
    }
    return respQueryEntity;
  },
});

useCmsEditorOption.use(option => {
  option.hooks.onError.use((e) => {
    const msg = e.message || JSON.stringify(e);
    $notice.error(msg);
  });
});
